package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"week3-exam1/cache"
	"week3-exam1/models"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	content := c.PostForm("content")
	author := c.PostForm("author")
	if name == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "参数不能为空",
		})
		return
	}
	data := models.Book{
		Name:    name,
		Content: content,
		Author:  author,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "1"))
	offset := (page - 1) * size

	var book []models.Book
	redis_key := "book_list_" + strconv.Itoa(page)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		models.DB.Offset(offset).Limit(size).Find(&book)
		jsonData, _ := json.Marshal(book)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &book)
	}
	var count int64
	models.DB.Model(&models.Book{}).Count(&count)
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "列表获取成功",
		"data": gin.H{
			"book":  book,
			"count": count,
		},
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var book []models.Book
	redis_key := "book_detail_" + id
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		models.DB.Where("id = ?", id).Find(&book)
		jsonData, _ := json.Marshal(book)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &book)
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "详情获取成功",
		"data": gin.H{
			"book": book,
		},
	})
	return
}

func Del(c *gin.Context) {
	id := c.Query("id")
	var book models.Book
	err := models.DB.Where("id = ?", id).Delete(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
